package com.lvyp.server.controller;

import com.lvyp.server.pojo.Admin;
import com.lvyp.server.pojo.AdminLoginParam;
import com.lvyp.server.pojo.RespBean;
import com.lvyp.server.service.IAdminService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

@Api(tags = "LoginController")
@RestController
public class LoginController {
    @Autowired
    private IAdminService adminService;

    /**
     * 登录接口
     * @param adminLoginParam 用户名，密码，验证码
     * @param request
     * @return
     */
    @ApiOperation(value = "登录成功之后返回token")
    @PostMapping("/login")
    public RespBean login(@RequestBody AdminLoginParam adminLoginParam,
                          HttpServletRequest request) {

        return adminService.login(adminLoginParam.getUsername(),
                adminLoginParam.getPassword(),
                adminLoginParam.getCode(),
                request);
    }

    @ApiOperation(value = "获取当前登录用户信息")
    @GetMapping("/admin/info")
    public Admin getAdminInfo(Principal principal){  // Principal获取当前登录对象，因为在service中将登录对象放到全局上下文里principal才能获取到

        if (null == principal) {
            return null;
        }
        String username = principal.getName();
        // 返回给前端的对象
        Admin admin = adminService.getAdminByUserName(username);
        admin.setPassword(null);  // 为了用户的安全，不能返回密码
        admin.setRoles(adminService.getRoles(admin.getId()));  // 返回用户的角色
        return admin;  // 返回给前端用户信息
    }

    @ApiOperation(value = "退出登录")
    @PostMapping("/logout")
    public RespBean logout(){
        // 直接返回提示字符串，退出登录功能由前端处理，前端会删除请求头里面的token
        return RespBean.success("注销成功！");
    }
}
